#!/bin/sh

## openssl version = 1.1.1
## SAN(Subject Alternative Name) : '''multi domain'''

bits=$1
shift 1

if ! echo $bits | grep -E "^[1-9][0-9]*$" &>/dev/null;then
    echo "[E] error bits shall be a number like 512 1024 2048 ..."
    exit 1
fi

cert_req(){
    # $1 .key
    # $2 .csr
    # $3 .conf
    :


}

gen_req_conf(){
#
    {
        cat <<EOF
[ req ]
# Options for the '''req''' tool ('''man req''').
prompt = no
default_bits        = ${bits}
distinguished_name  = req_distinguished_name
string_mask         = utf8only
# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = server_san_cert
#req_extensions     = server_san_cert

[ req_distinguished_name ]
countryName                 = $1
stateOrProvinceName         = $2
localityName                = $3
organizationName            = $4
organizationalUnitName      = $5
commonName                  = $6


EOF
        
        {
            cat <<EOF
[ server_san_cert ]
# Extensions for server certificates ('''man x509v3_config''').
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
EOF

            echo "[alt_names]"
            if [ -n "$SAN" ];then
                index=0
                for s in $SAN;do
                    echo "DNS.$index    =    $s"
                    let index++
                done
            fi
        } | tee "${root_dir}/$san_conf"

    } > "${root_dir}/${req_conf}"

}


root_dir="/data"
############
N=0
[ -e "${root_dir}/N.conf" ] && N="$(cat "${root_dir}/N.conf")" && let N++
echo -n "N="
echo $N | tee  "${root_dir}/N.conf"

# 1 conf
echo "[INFO] 1 gen conf"
commonName="$6"
SAN="$7"

san_conf="$commonName.$N.san.conf"
req_conf="$commonName.$N.req.conf"
server_key="$commonName.$N.${bits}.key.pem"
server_csr="$commonName.$N.csr.pem"
server_crt="$commonName.$N.crt.pem"
##

gen_req_conf  "$@" 
# CN   zhejiang   Yh   SmallGroupX   dev   "server.lan"

echo "# 1 done
"

# 2 key, -aes256|..|.. 2048|4096
## openssl genrsa -out xxx.key.pem 2048
## openssl genrsa -aes256 -out xxx.key.pem 2048
# bits = 512(512 maybe not OK) 1024 2048 4096...
echo "[INFO] gen .key"
openssl genrsa -out "${root_dir}/${server_key}" $bits

# 3 req <- key + conf
echo "
[INFO] gen .csr request"
openssl req -config "${root_dir}/${req_conf}" \
      -key "${root_dir}/${server_key}" \
      -new -sha256 \
      -out "${root_dir}/${server_csr}"

echo ""

# # # 2&3
# # echo "2&3 gen .key & .csr"
# echo "[INFO] 2&3"
# openssl req -newkey rsa:2048 -nodes -config "${req_conf}"  -keyout "2nd_${server_key}" -out "2nd_${server_csr}"
# # echo "# 2&3 -1"
# # openssl req -noout -text -in "${server_csr}" | grep -i dns
# # echo "# 2&3 -1#done "
# # echo "  ************** "

#############
if sh ./ssl_ca.sh sign $commonName;then
    (
        cd "${root_dir}"
        {
            echo "ln -sf $server_key server.latest.key.pem"
            echo "ln -sf $server_csr server.latest.csr.pem"
            echo "ln -sf $server_crt server.latest.crt.pem"
        } > mklink.sh 

    )


    sh check.sh md5 "${root_dir}/${server_key}" "${root_dir}/${server_csr}" "${root_dir}/${server_crt}"


    echo "[OK] cert is signed"
    echo "[OK] cert is signed"
    echo "[OK] cert is signed"
fi

